package com.sann.demo.dao.impl;

import com.sann.demo.dao.IAccountDao;
import com.sann.demo.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    JdbcTemplate jdbcTemplate;


    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = jdbcTemplate.query("select * from tb_account where id=?", new BeanPropertyRowMapper<Account>(Account.class), 1);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query("select * from tb_account where name like ?", new BeanPropertyRowMapper<Account>(Account.class), "%"+accountName+"%");
        if(accounts.isEmpty()) return null;
        if(accounts.size()>1) {
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update tb_account set name=?, money=? where id=?", account.getName(), account.getMoney(), account.getId());
    }
}
